import Axios from 'axios';
import router from '@/router';
import Vue from 'vue';
export default {
    state: {
        menus: [],
        isCollapse: false,
        selectedItem: null,
        tabsList: [],
        exculdeTag: []
    },
    actions: {
        async getUserMenu({ commit }) {
            let res = await Axios.get('/menusApi.json');
            commit('setUserMenu', res.data);
            return res.data;
        },
    },
    mutations: {
        // 存储菜单
        setUserMenu(state, menus) {
            state.menus = menus;
        },
        // 切换
        switch(state) {
            state.isCollapse = !state.isCollapse;
        },
        // 添加Tab
        addTab(state, route) {
            let able = state.tabsList.some(item => item.name === route.name);
            if (able) return;
            state.tabsList.push(route);
        },
        // 选中导航
        selectItem(state, value) {
            if (value.name !== 'home') {
                state.selectedItem = value;
                let result = state.tabsList.findIndex(item => item.name === value.name);
                if (result === -1) {
                    state.tabsList.push(value);
                } else {
                    state.selectedItem = null;
                }
            }
        },
        // 关闭导航
        CloseItem({ tabsList, exculdeTag }, { tagName, cur }) {
            let L = tabsList.length;
            if (L === 1) return;
            let result = tabsList.findIndex(item => item.name === tagName);
            if (result !== -1) {
                if (tagName === cur) {//如果删除的是当前tag
                    if (result === L - 1) {//同时是最后一个tag的时候跳到倒数第二个
                        router.push({ name: tabsList[L - 2].name })
                    } else {//其他的情况跳到最后一个
                        router.push({ name: tabsList[L - 1].name })
                    }
                }
                // 添加到排除的Tag
                exculdeTag.push(tagName);
                // 删除Tag
                tabsList.splice(result, 1);
                // 清空下一个排除的tag
                Vue.nextTick(() => {
                    exculdeTag.length = 0;
                })
            }
        }
    },
    getters: {
        // 获取菜单
        getMenu(state) {
            return state.menus;
        },
        //单项菜单
        aloneItem(state) {
            return state.menus.filter((item) => !item.childrens);
        },
        //菜单组
        pluralItem(state) {
            return state.menus.filter((item) => item.childrens);
        },
    }
}